package com.atguigu.cloud.controller;

import com.atguigu.cloud.apis.PayFeginApi;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @auther zzyy
 * @create 2023-11-13 14:54
 * Resilience4j CircuitBreaker 的例子
 */
@RestController
@Slf4j
public class OrderCircuitController {
    @Resource
    private PayFeginApi payFeignApi;

    @GetMapping(value = "/feign/pay/circuit/{id}")
    @CircuitBreaker(name = "cloud-payment-service", fallbackMethod = "myCircuitFallback")
    public String myCircuitBreaker(@PathVariable("id") Integer id) {
        return payFeignApi.myCircuit(id);
    }

    @GetMapping(value = "/feign/pay/bulk/{id}")
    @Bulkhead(name = "cloud-payment-service", fallbackMethod = "myCircuitFallback", type = Bulkhead.Type.SEMAPHORE)
    public String mybulkhead(@PathVariable("id") Integer id) {
        return payFeignApi.myCircuitBulkHead(id);
    }

    @GetMapping(value = "/feign/pay/bulk/pool/{id}")
    @Bulkhead(name = "cloud-payment-service", fallbackMethod = "myCircuitFallbackpool", type = Bulkhead.Type.THREADPOOL)
    public CompletableFuture<String> mybulkheadpoll(@PathVariable("id") Integer id) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> payFeignApi.myCircuitBulkHead(id));
        return future;
    }

    public CompletableFuture<String> myCircuitFallbackpool(int id, Throwable t) {
        // 这里是容错处理逻辑，返回备用结果
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            return "id:" + id + "获取失败";
        });
        return future;
    }

    //myCircuitFallback就是服务降级后的兜底处理方法
    public String myCircuitFallback(Throwable t) {
        // 这里是容错处理逻辑，返回备用结果
        log.error("myCircuitFallback,系统繁忙，请稍后再试-----/(ㄒoㄒ)/~~", t);
        return "myCircuitFallback，系统繁忙，请稍后再试-----/(ㄒoㄒ)/~~";
    }

    @GetMapping(value = "/feign/pay/ratelimit/{id}")
    @RateLimiter(name = "cloud-payment-service",fallbackMethod = "myRatelimitFallback")
    public String myBulkhead(@PathVariable("id") Integer id)
    {
        return payFeignApi.myRatelimit(id);
    }
    public String myRatelimitFallback(Integer id,Throwable t)
    {
        return "你被限流了，禁止访问/(ㄒoㄒ)/~~";
    }


}

